<?php

namespace app\home\controller;

use app\common\controller\Home;
use PHPMailer\PHPMailer\PHPMailer;
use think\Request;

class User extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
        $this->RecordModel = model('Record');
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $userid = $this->request->param('userid', 0);

        //方法之一，判断用户的数据的方法
        // $userList = $this->UserModel->where('id',$userid)->find();

        // $userList = !empty($userList) ? $userList : $this->LoginUser;

        // return $this->fetch("",[
        //     'userList' => $userList
        // ]);

        //另一个种判断用户的方法
        if ($userid) {
            $User = $this->UserModel->find($userid);

            if (!$User) {
                $this->error('该用户不存在');
            }

            //用户最近提问的帖子
            $postList = model('Post.Post')->where('userid',  $userid)->paginate(10, false, [
                'var_page' => 'page_post'
            ]);
            // halt($postList);

            //用户最近的回答
            $commentList = model('Post.Comment')->with(['post'])->where('comment.userid',  $userid)->paginate(4, false, [
                'type'     => 'Bootstrap',
                'var_page' => 'page_comment'
            ]);

            return $this->fetch('', [
                'userList' => $User,
                "postList" => $postList,
                "commentList" => $commentList
            ]);
        }
        $userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;



        //用户最近提问的帖子
        $postList = model('Post.Post')->where('userid',  $userid)->paginate(10, false, [
            'var_page' => 'page_post'
        ]);
        // halt($postList);

        //用户最近的回答
        $commentList = model('Post.Comment')->with(['post'])->where('comment.userid',  $userid)->paginate(4, false, [
            'type'     => 'Bootstrap',
            'var_page' => 'page_comment'
        ]);

        return $this->fetch("", [
            'userList' => $this->LoginUser,
            "postList" => $postList,
            "commentList" => $commentList
        ]);
    }

    /**
     * 显示设置资料
     *
     * @return \think\Response
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            // halt($this->LoginUser['content']);
            $action = $this->request->param('action', '');
            if ($action == 'profile') {
                $params = $this->request->param();

                //封装数据
                $data = [
                    'id' => $this->LoginUser['id'],
                    'nickname' => $params['nickname'],
                    'sex' => $params['sex'],
                    'province' => $params["province"],
                    'city' => $params["city"],
                    'district' => $params["district"],
                    'content' => $params['content']
                ];

                // halt($data);
                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    $this->error('更新基本资料失败');
                } else {
                    $this->success('更新基本资料成功', url('home/user/index'));
                }
            }
            if ($action == 'proPassword') {
                $params = $this->request->param();
                if ($params['pass'] != $params['repass']) {
                    $this->error('密码与确认密码不一致');
                }
                $password = md5($params['nowpass'] . $this->LoginUser['salt']);
                if ($password != $this->LoginUser['password']) {
                    $this->error('输入原密码错误');
                }
                $oldPassword = md5($params['pass'] . $this->LoginUser['salt']);
                if ($oldPassword == $this->LoginUser['password']) {
                    $this->error('新密码与原密码不能一致');
                }

                $salt = build_ranstr();
                $newPassword = md5($params['pass'] . $salt);
                $newData = [
                    'id' => $this->LoginUser['id'],
                    'password' => $newPassword,
                    'salt' => $salt,
                ];
                // halt($newData);
                $res = model('User.User')->isUpdate(true)->save($newData);
                if ($res) {
                    cookie('LoginUser', md5($newData['id'] . $newData['salt']));
                    $this->success('密码更新成功', url('home/user/profile'));
                } else {
                    $this->error('密码更新失败', url('home/user/profile'));
                }
            }
            if ($action == 'avatar') {
                $avatar = upload('avatar');
                // halt($avatar);

                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }

                $data = [
                    'id' => $this->LoginUser['id'],
                    'avatar' => $avatar['data']
                ];

                $result = $this->UserModel->isUpdate(true)->save($data);
                if ($result === FALSE) {
                    @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
                    $this->error('更新头像失败');
                } else {
                    @is_file('.' . $this->LoginUser['avatar']) && unlink('.' . $this->LoginUser['avatar']);
                    $this->success('更新头像成功');
                }
            }
            if ($action == 'cover') {
                $avatar = upload('cover');
                // halt($avatar);

                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }

                $data = [
                    'id' => $this->LoginUser['id'],
                    'cover' => $avatar['data']
                ];

                $result = $this->UserModel->isUpdate(true)->save($data);
                if ($result === FALSE) {
                    @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
                    $this->error('更新背景图片失败');
                } else {
                    @is_file('.' . $this->LoginUser['cover']) && unlink('.' . $this->LoginUser['cover']);
                    $this->success('更新背景图片成功');
                }
            }
        }

        //查询地区的省份
        $provinces = model('Region')->where(['grade' => 1])->select();

        //查询市区
        if ($this->LoginUser['province']) {
            $citys = model('Region')->where(['parentid' => $this->LoginUser['province']])->select();
        } else {
            $citys = [];
        }

        // 查询区
        if ($this->LoginUser['city']) {
            $districts = model('Region')->where(['parentid' => $this->LoginUser['city']])->select();
        } else {
            $districts = [];
        }

        $navTitle = '基本资料';

        // halt( $this->LoginUser);

        //查询地区里面的省份
        $provinces = model('Region')->where(['grade' => 1])->select();
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'provinces' => $provinces,
            'citys' => $citys,
            'districts' => $districts,
            // 'content' => $this->LoginUser['content']
        ]);
    }

    //签到
    public function sign()
    {
        if ($this->request->isPost()) {
            $action = $this->request->param('action', '');
            if ($action == 'signIn' && $this->request->isAjax()) {
                $point = $this->request->param('point', '');

                //查询用户积分
                $oldPoint = $this->UserModel->where(['id' => $this->LoginUser['id']])->value('point');
                $user_data = [
                    'id' => $this->LoginUser['id'],
                    'point' => $oldPoint
                ];

                //开启事务
                // model('Record')->startTrans();
                // $this->UserModel->startTrans();
                // model('SignIn')->startTrans();


                //查询最后一个插入的id
                // $RecordId = model('Record')->insertGetId("");

                // $RecordId = model('Record')->save();
                // halt($RecordId['id']);    // 输出当前插入数据的主键
                // $RecordId = model('Record')->count();
                $record_data = [
                    // 'id' => $RecordId + 1,
                    'userid' => $this->LoginUser['id'],
                    'point' => $oldPoint,
                    'createtime' => strtotime(date('Y-m-d H:i:s', time())),
                    'content' => '',
                    'state' => 4

                ];
                // halt($record_data);
                //在签到表中判断存在签到 和签到天数
                $SignInList = model('SignIn')->where('userId', $this->LoginUser['id'])->find();

                $sign_data = [
                    'id' => $SignInList['id'],
                    'num' => $SignInList['num'],
                    'signTime' => $SignInList['signTime'],
                    'addTime' => $SignInList['addTime']
                ];


                //获取当前时间的时间戳
                $now_time = strtotime(date('Y-m-d 0:0:0', time()));

                if ($SignInList['signTime'] == $now_time) {
                    $this->error('您今天已经签到了');
                } else {
                    //昨天0点时间戳
                    $prev_day = $now_time - 86400;
                    //明天0点时间戳
                    $next_day = $now_time + 86400;

                    $sign_data['signTime'] = $now_time;

                    //判断昨天是否签到过 也是判断是否连续签到
                    if ($SignInList['addTime'] == $prev_day) {
                        $sign_data['num'] = $sign_data['num'] + 1;

                        // if ($sign_data['num'] > 3) {
                        //     $point = $point + $point * 2;
                        // } 

                        $user_data['point'] = $user_data['point'] + $point;


                        $sign_data['addTime'] = $now_time;
                        $record_data['point'] = (int)$point;
                        $record_data['content'] = '【签到】' . date('Y-m-d H:i:s') . ' 签到 获得 ' . $point . ' 积分';
                        $resRec = model('Record')->validate('common/User/Record')->insert($record_data);

                        $result = model('SignIn')->isUpdate(true)->save($sign_data);
                        $res = $this->UserModel->isUpdate(true)->save($user_data);
                        if ($result === FALSE || $res === FALSE || $resRec == FALSE) {
                            // model('Record')->rollback();
                            // $this->UserModel->rollback();
                            // model('SignIn')->rollback();
                            $this->error('签到失败');
                        } else {
                            // model('Record')->commit();
                            // $this->UserModel->commit();
                            // model('SignIn')->commit();
                            $this->success('签到成功', null, $sign_data['num']);
                        }
                        // 如果昨天没有签到过则是断签 积分重置
                    } else {
                        $sign_data['num'] = 1;
                        $sign_data['addTime'] = $now_time;
                        $user_data['point'] = $user_data['point'] + $point;
                        $record_data['point'] = (int)$point;
                        $record_data['content'] = '【签到】' . date('Y-m-d H:i:s') . ' 签到 获得 ' . $point . ' 积分';
                        $resRec = model('Record')->validate('common/User/Record')->insert($record_data);
                        // halt($record_data);
                        // halt($resRec);
                        $result = model('SignIn')->isUpdate(true)->save($sign_data);
                        $res = $this->UserModel->isUpdate(true)->save($user_data);
                        if ($result === FALSE || $res === FALSE || $resRec == FALSE) {
                            // model('Record')->rollback();
                            // $this->UserModel->rollback();
                            // model('SignIn')->rollback();
                            $this->error('签到失败');
                        } else {
                            // model('Record')->commit();
                            // $this->UserModel->commit();
                            // model('SignIn')->commit();
                            $this->success('签到成功', null, $sign_data['num']);
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询地区
     *
     * @return \think\Response
     */
    public function area()
    {
        //
        if ($this->request->isAjax()) {
            $code = $this->request->param('code', '');
            $list = model('Region')->where(['parentid' => $code])->select();

            if (!$list) {
                $this->error('选择地区不存在');
            }
            $this->success('查询成功', null, $list);
        }
    }

    /**
     * 发送邮箱
     *
     * @return \think\Response
     */
    public function email()
    {
        if ($this->request->isAjax()) {
            $email = $this->request->param('email', '');
            //返回json的格式
            //return json($email);
            // halt($email);
            /**
             * 判断该邮箱是否注册了
             * 生成随机字符串
             * 设置session
             * 在随机字符串发送该邮箱
             * 手动输入字符串
             * 注册功能，获取session那个字符串以及接收到表单验证码
             */

            $User = $this->UserModel->where(['email' => $email])->find();

            if (!$User) {
                $this->error("该邮箱不存在");
            }
            $Email = md5($User['email'] . $User['salt']);

            $content = "<a href='http://www.tp5.com/home/index/auth?email=$Email'>点击认证</a>";

            $mail = new PHPMailer(true);

            //开启SMTP
            $mail->isSMTP(true);

            // 开启认证
            $mail->SMTPAuth = true;

            // SMTP服务器 163 => smtp.163.com
            $mail->Host = 'smtp.qq.com';

            //账号
            $mail->Username = '513104975@qq.com';

            //密码 => 不是邮箱密码 是开启smtp的授权码
            $mail->Password = 'asnelcxkkgdvbhcg';

            //端口 服务器需要开启465端口
            $mail->Port = 465;

            //协议
            $mail->SMTPSecure = 'ssl';

            //发件人邮箱
            $mail->From = '513104975@qq.com';

            //发件人名字
            $mail->FromName = 'ASK论坛';

            //接收回复的邮箱
            $mail->addReplyTo('513104975@qq.com', 'ASK论坛');

            //收件人
            $mail->addAddress($User['email'], $User['nickname']);

            //邮箱主题
            $mail->Subject = "账号认证";

            //设置多少个字符换行 80字符
            $mail->WordWrap = 80;

            //发送html的内容
            $mail->msgHTML($content);

            $result = $mail->send();

            if ($result === FALSE) {
                $this->error('发送邮件失败');
            } else {
                $this->success('发送邮件成功');
            }
        }

        $navTitle = '基本资料';

        return $this->fetch('', [
            'navTitle' => $navTitle
        ]);
    }


    /**
     * 显示设置列表
     *
     * @return \think\Response
     */
    public function record()
    {
        $recordList = model('Record')->order('createtime', 'desc')->where(['userid' => $this->LoginUser['id']])->paginate(10);
        // halt($recordList);

        $StateOne = model('Record')->order('createtime', 'desc')->where(['userid' => $this->LoginUser['id'], 'state' => 1])->paginate(10);
        $StateTwo = model('Record')->order('createtime', 'desc')->where('state', 2)->where(['userid' => $this->LoginUser['id']])->paginate(10);
        $StateThree = model('Record')->order('createtime', 'desc')->where('state', 3)->where(['userid' => $this->LoginUser['id']])->paginate(10);
        $StateFour = model('Record')->order('createtime', 'desc')->where('state', 4)->where(['userid' => $this->LoginUser['id']])->paginate(10);
        // echo model('Record')->getlastsql();
        // exit;
        // halt(count($recordList));
        $allCount = count($StateOne) + count($StateTwo) + count($StateThree) + count($StateFour);

        $navTitle = '积分记录';

        return $this->fetch('', [
            'navTitle' => $navTitle,
            'AllRecord' => $allCount,
            'recordList' => $recordList,
            'StateOne' => $StateOne,
            'StateTwo' => $StateTwo,
            'StateThree' => $StateThree,
            'StateFour' => $StateFour
        ]);
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $recordid = $this->request->param('recordid', 0);

            //deletetime is null
            $record = model('Record')->find($recordid);
            //查询sql语句
            // echo $this->PostModel->getlastsql();
            // exit;

            if (!$record) {
                $this->error("消费记录不存在，无法删除");
            }

            //$result = $post->delete();
            $result = model('Record')->destroy($recordid);
            if ($result === FALSE) {
                $this->error('删除失败');
            }

            $this->success('删除成功', url('home/user/record'));
        }
    }
    /**
     * 用户退出
     *
     * @return \think\Response
     */
    public function logout()
    {
        cookie('LoginUser', null);
        $this->success('退出成功', url('home/index/index'));
    }

    /**
     * 显示用户中心
     *
     * @return \think\Response
     */
    public function collect()
    {
        $flag = $this->request->param('collect', 'collected');
        // halt($params['collect']);
        $userPost = model('Post.Post')->with(['user'])->order('createtime', 'desc')->where(['post.userid' => $this->LoginUser['id']])->paginate(10);
        $postList = model('Collect')->with(['post'])->order('createtime', 'desc')->where(['collect.userid' => $this->LoginUser['id']])->paginate(10, false, [
            'var_page' => 'page_collect',
        ]);

        $navTitle = '收藏记录';

        return $this->fetch('', [
            'navTitle' => $navTitle,
            "postList" => $postList,
            "userPost" => $userPost,
            'flag' => $flag
        ]);
    }

    /**
     * 显示消息列表
     *
     * @return \think\Response
     */
    public function message()
    {
        $postList = model('Post.Post')->where(['userid' => $this->LoginUser['id']])->select();
        $arrList = [];
        for ($i = 0; $i < count($postList); $i++) {
            $arrList[] = model('Post.Comment')->with(['user', 'post'])->order('comment.createtime', 'desc')->group('comment.userid')->where(['comment.postid' => $postList[$i]['id']])->select();
        }

        // $userList = model('Post.Comment')->where()
        // halt($arrList);
        $navTitle = '我的消息';

        return $this->fetch('', [
            'navTitle' => $navTitle,
            'arrList' => $arrList
        ]);
    }
}
